package it.apiconsulting.live.controller;


import it.apiconsulting.live.model.Cliente;
import it.apiconsulting.live.util.HibernateUtil;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.classic.Session;


public class ClienteManager extends HibernateUtil {

	public Cliente add(Cliente cliente) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(cliente);
		session.getTransaction().commit();
		return cliente;
	}
	public Cliente delete(Long id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Cliente cliente = (Cliente) session.load(Cliente.class, id);
		if(null != cliente) {
			session.delete(cliente);
		}
		session.getTransaction().commit();
		return cliente;
	}

	public List<Cliente> list() {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Cliente> clienti = null;
		try {
			
			Query query = session.createQuery("from Cliente");
			clienti = (List<Cliente>)query.list();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return clienti;
	}
	
	public Cliente update(Cliente cliente) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.update(cliente);
		session.getTransaction().commit();
		return cliente;
	}
	
	public Cliente getClienteById(Long idCliente) {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Cliente cliente = null;
		try {
			
			Query query = session.createQuery("from Cliente where id = "+ idCliente);
			cliente = (Cliente)query.uniqueResult();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return cliente;
	}
}
